package com.puboot.module.admin.controller;

import com.puboot.common.util.Constants;
import com.puboot.common.util.CoreConst;
import com.puboot.common.util.ResultUtil;
import com.puboot.module.admin.model.BizAboutUs;
import com.puboot.module.admin.model.User;
import com.puboot.module.admin.service.BizAboutUsService;
import com.puboot.module.admin.vo.base.ResponseVo;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("aboutus")
@AllArgsConstructor
public class BizAboutUsController {

    private final BizAboutUsService aboutUsService;


    @GetMapping("/add")
    public String addAboutUs(Model model) {
        BizAboutUs bizAboutUs = aboutUsService.findByStatus(Constants.STATE_VAILD);
        model.addAttribute("bizAboutUs", bizAboutUs);
        return CoreConst.ADMIN_PREFIX + "aboutus/about";
    }

    @PostMapping("/add")
    @ResponseBody
    @Transactional
    @CacheEvict(value = "aboutUs", allEntries = true)
    public ResponseVo add(BizAboutUs bizAboutUs, Integer[] tag) {
        try {
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            if(bizAboutUs.getId() != null){
                BizAboutUs old = aboutUsService.getById(bizAboutUs.getId());
                old.setStatus(Constants.STATE_INVAILD);
                old.setUpdateTime(new Date());
                old.setUpdateUserId(user.getUserId());
                aboutUsService.updateById(old);
            }
            bizAboutUs.setCreateUserId(user.getUserId());
            bizAboutUs.setCreateTime(new Date());
            bizAboutUs.setStatus(Constants.STATE_VAILD);
            aboutUsService.save(bizAboutUs);
            return ResultUtil.success("保存成功");
        } catch (Exception e) {
            return ResultUtil.error("保存失败");
        }
    }


}
